﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Nirvana
{
    /// <summary>
    /// 多边形雷达图形
    /// </summary>

    [AddComponentMenu("Nirvana/UI/Effects/Radar Chart Polygon")]
    public class RadarChartPolygon : Graphic
    {

        [SerializeField]
        [Range(3f, 30f)]
        private int verticesCount = 5;

        /// <summary>
        /// 顶点最大厚度
        /// </summary>
        [SerializeField]
        [Range(0f, 1f)]
        private float maxVolume = 1f;

        /// <summary>
        /// 每个顶点的厚度
        /// </summary>
        [SerializeField]
        private float[] volumes;

        public void SetVolume(int index,float value)
        {
            if(this.volumes.Length < index)
            {
                Array.Resize<float>(ref this.volumes, index + 1);
            }
            this.volumes[index] = value;
            this.SetVerticesDirty();
        }

        public float GetVolume(int index)
        {
            if(this.volumes.Length - 1 < index)
            {
                return 0;
            }

            float value = this.volumes[index];
            return value <= this.maxVolume ? value : this.maxVolume;
        }

        private Vector2 ModifyVertex(float x,float y)
        {
            Vector2 pivot = this.rectTransform.pivot;
            Rect rect = this.rectTransform.rect;
            Vector2 vertex = Vector2.zero;
            vertex.x -= pivot.x;
            vertex.y -= pivot.y;
            vertex.x += x;
            vertex.y += y;
            vertex.x *= rect.width;
            vertex.y *= rect.height;
            return vertex;
        }

        /// <summary>
        /// 当一个UI元素生成顶点数据时会调用OnPopulateMesh(VertexHelper vh)函数，
        /// 我们可以在这个函数中修改顶点的数据或者获取顶点的数据。
        /// </summary>
        protected override void OnPopulateMesh(VertexHelper vh)
        {
            vh.Clear();
            if (this.volumes == null || this.maxVolume == 0) return;
            UIVertex simpleVert = UIVertex.simpleVert;
            simpleVert.color = this.color;
            Vector2 vertex = this.ModifyVertex(0.5f, 0.5f);
            simpleVert.position = vertex;
            vh.AddVert(simpleVert);

            float avgAngle = 360f / this.verticesCount;
            for(int i = 0; i < this.verticesCount; i++)
            {
                float angle = (90 - avgAngle * i) * Mathf.Deg2Rad;
                float volume = this.GetVolume(i) * 0.5f;
                float x = 0.5f + Mathf.Cos(angle) * volume;
                float y = 0.5f + Mathf.Sin(angle) * volume;
                Vector2 pos = this.ModifyVertex(x, y);
                simpleVert.position = pos;
                vh.AddVert(simpleVert);
                vh.AddTriangle(0, i + 1, (i + 1) % this.verticesCount + 1);
            }
        }

    }
}

